<template>
  <view class="container">
    <view v-if="videoPlay.palyType===0 && topBoxShow" :style="topBoxStyle" class="top-box">
		<view :style="toIndexStyle" class="to-index" @click="toSindex">
			<image mode="aspectFill" src='https://wechat-pictures-1301970825.file.myqcloud.com/shop/oUser/toIndex.png'></image>
		</view>
      <view :style="topTitleStyle" class="top-title">视频答题</view>
    </view>
    <video-play-view v-if="videoPlay.src" @videoPlays="setvideoPlay" @videoEnd="videoEnd"
                     @setOrientation="setOrientation" :videoPlay="videoPlay" :videoInfo="videoInfo"></video-play-view>
    <view class="content" v-if="videoPlay.palyType===0 && !showLogin && videoPlay.src">
      <view class="video-title">{{ videoInfo.titleCus }}</view>
      <view class="video-date">答题截止时间：
        <text>{{ videoInfo.endTime }}</text>
        <image :src="image_hosts+'/date.png'"></image>
      </view>
      <view class="video-message-box">
        <view class="message-item" v-if="videoInfo.appearScene===2 || videoInfo.appearScene===0">
          <image :src="image_hosts+'/gangtan.png'"></image>
          播放完成后才能开始答题
        </view>
        <view class="message-item" v-if="videoInfo.appearScene===2 || videoInfo.appearScene===0">
          <image :src="image_hosts+'/gangtan.png'"></image>
          答题完成后，点击底部“提交”按钮完成答题
        </view>
        <view class="message-item" v-if="videoInfo.appearScene===2 || videoInfo.appearScene===1">
          <image :src="image_hosts+'/gangtan.png'"></image>
          视频观看过程中需要答题，请认真观看
        </view>
      </view>
      <view class="answer-box" v-if="videoInfo.appearScene===2 || videoInfo.appearScene===0">
        <answer-subject :questionList="videoInfo.questionList"></answer-subject>
      </view>
    </view>
    <answer-loading :show="showLogin"></answer-loading>
  </view>
</template>

<script>
import answerSubject from "@/pages/newAnswer/components/answer-subject.vue";
import videoPlayView from "@/pages/newAnswer/components/video-play.vue";
import answerSuccess from "@/pages/newAnswer/components/answer-success.vue";
import answerLoading from "@/pages/newAnswer/components/answer-loading.vue";

export default {
  components: {
    answerSubject,
    videoPlayView,
    answerSuccess,
    answerLoading
  },
  data() {
    return {
      videoPlay: {
        width: '100%',
        height: '422rpx',
        src: "",
        palyType: 0,
      },
      videoInfo: {},
      ids: [],
      menuInfo: uni.getStorageSync('menuInfo'),
      topTitleStyle: '',
      topBoxStyle: '',
      image_hosts: this.image_host + 'videoAnswer',
      is_look: true, // 是否链接失效 判断code存不存在
      requestCode: '', // 服务器端code
      videoId: 0, // 视频id
      oldPlayTime: 0,
      g_z_code: "", //公众号code
      is_show_info: true,
      activityId: '', // 活动id
      reward: null,
      showLogin: false,
      topBoxShow: true,
	  toIndexStyle:''
    };
  },
  onResize(res) {
    let _this = this
    if (res.deviceOrientation === 'landscape') {
      _this.videoPlay.height = "100vh"
      _this.videoPlay.palyType = 1
    } else {
      _this.videoPlay.height = "422rpx"
      _this.videoPlay.palyType = 0
    }
  },
  onLoad(req) {
    this.topBoxStyle = `height: ${this.menuInfo.contentTop};padding-top: ${this.menuInfo.menuTop};`
    this.topTitleStyle = `height: ${this.menuInfo.menuHeight};`
	this.toIndexStyle=`height: ${this.menuInfo.menuHeight};width: ${this.menuInfo.menuHeight};top: ${this.menuInfo.menuTop};`
    if (uni.getStorageSync("requestCode") !== req.requestCode) {
      let menuInfo = uni.getStorageSync('menuInfo')
      uni.clearStorage();
      uni.setStorageSync('menuInfo', menuInfo)
    }
    this.g_z_code = req.g_z_code
    if (req.requestCode) {
      this.requestCode = req.requestCode;
      uni.setStorageSync("requestCode", this.requestCode)
    } else {
      this.is_look = false;
    }
    this.videoId = req.videoId;
    this.$dadian("");
  },
  onShow() {
    let that = this
    // 1秒之后还没有请求到数据显示加载效果
    setTimeout(() => {
      if (!that.videoPlay.src) {
        that.showLogin = true
      }
    }, 700)
    //#ifdef H5
    that.g_z_login()
    that.topBoxShow = false
    //#endif
    //#ifdef MP-WEIXIN
    that.login();
    // #endif
  },
  methods: {
	  toSindex()
	  {
		  uni.switchTab({
		  	url:'/pages/sindex/index'
		  })
	  },
    // 视频观看方式
    setOrientation() {
      //#ifdef H5
      uni.showToast({
        title: '公众号版本暂不支持全屏',
        icon: 'none'
      })
      return
      //#endif
      const isVertical = this.videoPlay.palyType; // 根据你的需求，获取横竖屏状态
      const orientation = isVertical ? 'portrait' : 'landscape'; // 根据横竖屏状态设置相应的方向
      let _this = this;
      wx.setPageOrientation({
        orientation: orientation,
        success: function (res) {
          if (orientation === 'landscape') {
            _this.videoPlay.height = "100vh"
            _this.videoPlay.palyType = 1
          } else {
            _this.videoPlay.height = "422rpx"
            _this.videoPlay.palyType = 0
          }
        },
        fail: function (res) {
          console.log('屏幕方向设置失败');
        }
      });
    },
    // 登录 检测是否答题等信息
    login() {
      var that = this;
      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          that.loginTwo(loginRes.code);
        },
      })

    },

    //公众号登陆
    g_z_login() {
      if (this.g_z_code) {
        this.loginTwo(this.g_z_code)
      } else {
        uni.setStorageSync("gzh_url", window.location.href)
        uni.setStorageSync('toVideo', true)
        uni.reLaunch({
          url: "/pages/login/gzh_login"
        })
      }
    },
    //登陆接口
    loginTwo(code) {
      let that = this;
      let data = {
        code: code,
        requestCode: this.requestCode
      };
      //#ifdef H5
      data.isH5 = 1;
      //#endif
      this.$NoteApi.doRequest("get", "login", data, 'json').then(async res => {
        // 跨店
        if (res.data.code === 408) {
          this.is_show_info = false;
          uni.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false,
            success() {
              uni.switchTab({
                url: '/pages/sindex/index'
              })
            }
          })
          return
        }
        //不再活动范围内
        if (res.data.code === 704) {
          this.is_show_info = false;
          uni.showModal({
            title: '提示',
            content: '不在活动参与范围内',
            showCancel: false,
            success() {
              uni.switchTab({
                url: '/pages/sindex/index'
              })
            }
          })
          return
        }
        // 活动结束
        if (res.data.code === 409) {
          uni.reLaunch({
            url: '/pages/newAnswer/endTwo?code=' + this.requestCode + '&video_id=' +
                this.videoId
          })
          return
        }
        if (res.data.code === 0) {
          this.activityId = res.data.data.activityId;
          var invitorInfo = res.data.data.invitorInfo;
          uni.setStorageSync("token", res.data.data.token)
          uni.setStorageSync("userInfo", res.data.data);

          // try {
          // 	const hasTaskEnterLimits = await this.getTaskEnterLimits();
          // 	if (hasTaskEnterLimits) {
          // 		const activityDetail = await this.getActivityDetail();
          // 		this.reward = activityDetail.reward / 100;
          // 		return;
          // 	}
          // } catch (error) {}

          // 1 新用户 去注册 0 老用户
          if (res.data.data.isNew === 1) {
            //#ifdef H5
            uni.showModal({
              content: '您还未注册成为本店会员，请到人康课堂小程完成注册后访问该链接',
              title: "提示"
            })
            return false;
            //#endif
            uni.navigateTo({
              url: '/pages/newAnswer/register?sheng=' + invitorInfo.deptProvince +
                  '&shi=' + invitorInfo.deptCity + '&deptName=' + invitorInfo
                      .deptName + '&invitorCode=' + invitorInfo.invitorCode +
                  '&requestCode=' + this.requestCode
            })
          } else {
            // 判断是否重复答题
            if (res.data.data.hasDone === 1) {
              uni.reLaunch({
                url: '/pages/newAnswer/endThree?code=' + this.requestCode +
                    '&video_id=' + this.videoId + '&activityId=' + this.activityId
              })
            } else {
              that.getIds();
              // that.getVideoInfo();
            }

          }
        } else {
          if (data.isH5 === 1 && data.code) {
            let url = window.location.origin + window.location.pathname +
                '#/pages/newAnswer/index?requestCode=' + data.requestCode + '&videoId=' + this
                    .videoId
            window.location.href = url
          }
          uni.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      })
    },
    //  第一次，不存在 / ==[]，直接[] 调用，成功后调用添加
    //  第二次，
    // 有就放 没就直接请求 ids==[]
    getIds() {
      let that = this;
      let answer_info = uni.getStorageSync('user_answers');
      for (let i = 0; i < answer_info.length; i++) {
        if (that.videoId === answer_info[i].videoId) {
          that.ids = answer_info[i].answers
        }
      }
      that.getVideoInfo();
    },
    // 获取视频信息详情
    getVideoInfo() {
      let that = this;
      let data = {
        videoId: Number(this.videoId),
        questionIds: that.ids,
      };
      that.$NoteApi.doRequest("post", "ruiVideo/detail", data, 'json').then(res => {
        this.showLogin = false
        if (res.data.code === 0) {
          this.videoInfo = res.data.data;
          this.videoPlay.src = res.data.data.videoAddress
          if (this.ids.length === 0) {
            that.set_Storage();
          }
        }
      }).catch(err => {
        this.showLogin = false
      })
    },
    // 如果第一次看当前视频 设置缓存 答对后删除
    set_Storage() {
      let that = this,
          setIds = [];
      for (let i = 0; i < that.videoInfo.questionList.length; i++) {
        that.videoInfo.questionList[i].all_choose = []
        setIds.push(that.videoInfo.questionList[i].id)
      }
      let get_arr = uni.getStorageSync('user_answers');
      if (!get_arr) get_arr = []
      get_arr.push({
        videoId: that.videoId,
        answers: setIds
      })
      this.ids = setIds;
      uni.setStorage({
        key: 'user_answers',
        data: get_arr
      });
    },
    // 视频结束的时候触发
    videoEnd() {
      var that = this;
      this.actionReport(4);
      uni.removeStorageSync("videoTime" + this.videoInfo.id);
      this.sendVideoEndLog()
      uni.reLaunch({
        url: '/pages/newAnswer/answer?code=' + this.requestCode + "&videoId=" + this.videoId +
            '&activityId=' + this.activityId + '&ids=' + encodeURIComponent(this.ids)
      })
    },
    async sendVideoEndLog() {
      let data = {
        code: this.requestCode,
        videoId: this.videoId
      }
      let res = await this.$javaCircle.doRequest("post", 'vs/ruiVideo/video/report', data, 'json');
      console.log(res, '上报观看完成')
    },
    // 获取入口权限
    getTaskEnterLimits() {
      return this.$request("marketing/user/activity/available", {
        params: {
          source: "Popup",
          activityType: "New_People_Task"
        }
      })
          .then(data => data.result).catch(() => null);
    },
    // 去新人任务页面
    goToNewPeopleTask() {
      uni.redirectTo({
        url: '/pages/newPeopleTask/index'
      });
    },
    // 获取活动详情
    getActivityDetail() {
      return this.$request("marketing/user/activity", {
        method: "GET",
        params: {
          activityType: "New_People_Task"
        }
      })
          .then(data => data)
          .catch(() => null);
    },
    // 视频开始的时候触发
    setvideoPlay() {
      this.actionReport(3);
    },
    // 行为上报
    actionReport(type) {
      var that = this;
      if (type == 3) {
        var data = {
          videoId: this.videoId,
          action: 3,
          entrance: 100,
        }
      } else {
        var data = {
          videoId: this.videoId,
          action: 4,
          duration: this.oldPlayTime,
          entrance: 100,
          fromChicken: 0,
        };
      }
      that.$NoteApi.doRequest("post", "action/report", data, 'json').then(res => {
        if (res.data.code == 0) {

        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  box-sizing: border-box;
  padding-bottom: env(safe-area-inset-bottom);
  display: flex;
  flex-direction: column;
}

.top-box {
  width: 100%;
  text-align: center;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  font-size: 32upx;
  color: #353535;
  font-weight: 500;
  position: relative;
}

.top-title {
  display: flex;
  align-items: center;
}

.content {
  flex: 1;
  overflow: auto;
  box-sizing: border-box;
  padding: 30upx;
}

.video-title {
  font-size: 42upx;
  color: #000000;
  font-weight: 500;
}

.video-date {
  display: flex;
  align-items: center;
  background-color: #EFF5FC;
  border-radius: 4upx;
  padding: 2upx 8upx;
  font-size: 28upx;
  width: 532upx;
  margin-top: 20upx;

  text {
    color: #F65D1B;
  }

  image {
    width: 20upx;
    height: 24upx;
    margin: 0 auto;
  }
}

.video-message-box {
  width: 100%;
  border-radius: 8upx;
  box-sizing: border-box;
  padding: 16upx 16upx 8upx 16upx;
  background-color: #E9F7EB;
  margin-top: 31upx;

  .message-item {
    font-size: 30upx;
    color: #01BD54;
    margin-bottom: 8upx;
    display: flex;
    align-items: center;
    font-weight: 500;

    image {
      width: 30upx;
      height: 30upx;
      margin-right: 8upx;
    }
  }
}

.answer-box {
  margin-top: 42upx;
  overflow: auto;
}
.to-index{
	position: absolute;
	top: 0;
	left: 20upx;
	display: flex;
	align-items: center;
	justify-content: center;
	image{
		width: 60%;
		height: 60%;
	}
}
</style>
